import { defineStore } from 'pinia'
import { login, logout, getCurrentUser } from '@/api/auth'
import { setToken, getToken, removeToken, setUserInfo, getUserInfo, removeUserInfo } from '@/utils/auth'
import { ElMessage } from 'element-plus'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    userInfo: getUserInfo(),
    roles: [],
    permissions: []
  }),

  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,

    // 获取用户角色
    getUserRoles: (state) => state.userInfo?.roles || [],

    // 获取用户权限
    getUserPermissions: (state) => state.userInfo?.permissions || [],

    // 是否为管理员
    isAdmin: (state) => {
      const roles = state.userInfo?.roles || []
      return roles.some(role => role.roleCode === 'ROLE_ADMIN')
    },

    // 是否为员工
    isEmployee: (state) => {
      const roles = state.userInfo?.roles || []
      return roles.some(role => role.roleCode === 'ROLE_EMPLOYEE')
    }
  },

  actions: {
    // 用户登录
    async login(loginForm) {
      try {
        const response = await login(loginForm)

        if (response.success) {
          const data = response.data

          // 保存token和用户信息
          this.token = data.token
          this.userInfo = data.userInfo

          setToken(data.token)
          setUserInfo(data.userInfo)

          // 检查自动兑换结果并显示通知
          if (data.autoRedeemResult && data.autoRedeemResult.successCount > 0) {
            const totalAmount = data.autoRedeemResult.totalAmount || 0
            ElMessage.success(`您已收到发放的福利卡，总金额：¥${totalAmount}`)
          }

          return { success: true, data }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('登录失败:', error)
        return { success: false, message: error.message }
      }
    },

    // 用户登出
    async logout() {
      try {
        await logout()
      } catch (error) {
        console.error('登出请求失败:', error)
      } finally {
        // 无论请求是否成功，都清除本地数据
        this.token = ''
        this.userInfo = null
        this.roles = []
        this.permissions = []

        removeToken()
        removeUserInfo()
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await getCurrentUser()

        if (response.success) {
          this.userInfo = response.data
          setUserInfo(response.data)
          return response.data
        } else {
          throw new Error(response.message)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果获取用户信息失败，可能是token过期，清除登录状态
        this.logout()
        throw error
      }
    },

    // 重置状态
    resetState() {
      this.token = ''
      this.userInfo = null
      this.roles = []
      this.permissions = []

      removeToken()
      removeUserInfo()
    },

    // 刷新用户信息
    refreshUserInfo() {
      if (this.token) {
        return this.getUserInfo()
      }
    }
  }
})